﻿using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Resources;
using System.Xml.Linq;
using System.Web.UI;
using System.Reflection;

namespace System.Web.Mvc
{
    /// <summary>
    /// Author：Bruce
    /// Blog：   http://coolcode.cnblogs.com
    /// </summary>
    public static class LocalizationHelpers
    {
        /// <summary>
        /// 在 Html 中直接使用
        /// </summary>
        /// <param name="htmlhelper"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string Lang(this HtmlHelper htmlhelper, string key)
        {
            return GetLangString(key);
        }

        /// <summary>
        /// 在js中使用
        /// </summary>
        /// <param name="htmlhelper"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string LangOutJsVar(this HtmlHelper htmlhelper, string key)
        {
            string langstr = GetLangString(key);
            return string.Format("var {0} = '{1}'", key, langstr);

        }

        /// <summary>
        /// Controller中使用
        /// </summary>
        /// <param name="control"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string Lang(this Controller control, string key)
        {
            return GetLangString(key);
        }

        public static string Lang(this HttpContextBase httpContext, string key)
        {
            return GetLangString(key);
        }

        public static string Lang(this Control control, string key)
        {
            return GetLangString(key);
        }

        private static string GetLangString(string key)
        {
            string Language = "zh-CN";
            HttpRequest Request = HttpContext.Current.Request;
            /*检查cookies是否有用户的语言设置*/
            if (Request.Cookies["Language"] != null)
                Language = Request.Cookies["Language"].Value;
            /*如果cookies中没有就取客户端的语言*/
            else if (Request.UserLanguages.Length > 0)
            {
                Language = Request.UserLanguages[0].ToLower();
            }
            System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(Language);
            ResourceManager rm = new ResourceManager("Base.Localization." + Language, Assembly.GetAssembly(typeof(Base.Localization.zh_CN)));
            return rm.GetString(key);

        }
    }

}